<?php

namespace app\api\service;

/*
 签名规则
 1，按照请求参数去除没有取值的key，并按照key升序
 2，把参数转化成url get参数形式拼接上app_secret 和nonce随机串，然后md32 再转成小写格式
 3，请求的时候 参考 getSignParam 把做参数处理
*/
class ApiSignCheck extends CommonService
{
    private $config;

    /*

      config [app_key=>''  app_secret=>'','version'=>'']
    */
    public function __construct($config)
    {
        $this->config = $config;
    }

    /*
    加密
    param 请求参数
    */

    public function getSign(array $param, $nonce)
    {
        unset($param['']);
        $param = array_filter($param);
        ksort($param);

        return strtolower(md5(http_build_query($param).'&app_secret='.$this->config['app_secret']).$nonce);
    }

    /*
     返回 附带签名的请求格式
    */
    public function getSignParam(array $param, $nonce)
    {
        $data['sign'] = $this->getSign($param, $nonce);
        $data['app_key'] = $this->config['app_key'];
        $data['nonce'] = $nonce;
        $data['data'] = $param;
        $data['version'] = $this->config['version'];

        return $param;
    }

    /*
     校验sign
     $param 接收到参数
    */
    public function checkSign($param)
    {
        try {
            $sign = $param['sign'];
            if ($this->getSign($param['data'], $param['nonce'] ?? '') != $sign) {
                return $this->inValiReturn('校验失败');
            }
        } catch (\Exception $e) {
            return $this->inValiReturn(getExceptionMsg($e));
        }

        return $this->valiReturn('检验成功');
    }
}
